package jvm;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 * 自定义 ClassLoader, 只需要重写 findClass 方法即可
 *
 * 正常运行条件我们电脑有 /home/smqk/jvm/Hello.class 文件
 */
public class MyClassLoader extends ClassLoader {


    public static void main(String[] args) {
        MyClassLoader myClassLoader = new MyClassLoader();

        try {
            Class<?> clazz = myClassLoader.loadClass("jvm.Hello");

            Method print = clazz.getMethod("print");
            print.invoke(clazz.newInstance());

            System.out.println(clazz.getClassLoader());     // jvm.MyClassLoader@2503dbd3
            System.out.println(MyClassLoader.class.getClassLoader());   // sun.misc.Launcher$AppClassLoader@659e0bfd
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        String path = name.replace(".", "/").concat(".class");
        File file = new File("/home/smqk/", path);

        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int b = 0;
            while ((b = fis.read()) != -1) {
                baos.write(b);
            }

            byte[] bytes = baos.toByteArray();
            System.out.println(bytes.length);

            fis.close();
            baos.close();

            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.findClass(name);   // throws ClassNotFoundException
    }

}



// Hello.java 文件如下：
// 编译生成字节码文件： javac -d . Hello.java
/*
package jvm;
public class Hello{
    public void print(){
        System.out.println("hello print");
    }
}
*/